import React, { useReducer, useCallback, useEffect } from 'react';
import Input from './Input'
import List from './List'
import { ITodo, IState, ACTION_TYPE } from './typings';
import { todoReducer } from './reducer';

const TodoList = () => {
    const init = (initTodoList: ITodo[]): IState => {
        return {
            todoList: initTodoList
        }
    };
 
    const [state, dispatch] = useReducer(todoReducer, JSON.parse(localStorage.getItem('todoList') ?? '[]'), init);
    const addTodo = useCallback((todo: ITodo): void => {
        dispatch(({
            type: ACTION_TYPE.ADD_TODO,
            payload: todo
        }))
    },[]);

    const removeTodo = useCallback((id: number):void => {
        dispatch({
            type: ACTION_TYPE.REMOVE_TODO,
            payload: id
        })
    },[]);

    const toggleTodo = useCallback((id: number):void => {
        dispatch({
            type: ACTION_TYPE.TOGGLE_TODO,
            payload: id
        })
    },[])
    // 解决刷新数据丢失问题
    useEffect(()=>{
        localStorage.setItem('todoList', JSON.stringify(state.todoList));
    },[state.todoList])
    return (
        <div>
           <Input 
               todoList={state.todoList}
               addTodo={addTodo}
           />
           <List 
               todoList={state.todoList}
               removeTodo={removeTodo}
               toggleTodo={toggleTodo}
           />
        </div>
    )
}

export default TodoList;
